package service

import (
	"fly/global"
	"fly/helper"
	"fly/models"
	"fly/resp"
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/condition"
	"github.com/duke-git/lancet/v2/convertor"
	"net/url"
)

const (
	AirportCacheSimple = "AirportCacheSimple:%d"
)

type AirportService struct {
	BaseService
	SysDictService SysDictService
}

func (c *AirportService) GetPaginateData(params url.Values) ([]*models.Airport, Pagination) {
	//搜索、查询字段赋值
	c.WhereField = append(c.WhereField, new(models.Airport).WhereField()...)
	var data []*models.Airport
	o := orm.NewOrm().QueryTable(new(models.Airport))
	_, err := c.PaginateAndScopeWhere(o, params, func(cond *orm.Condition) *orm.Condition {
		startTime := params.Get("startTime")
		endTime := params.Get("endTime")
		if len(startTime) > 0 && len(endTime) > 0 {
			start, err1 := convertor.ToInt(startTime)
			end, err2 := convertor.ToInt(endTime)
			if err1 == nil && err2 == nil {
				cond = cond.And("create_time__gte", helper.Milli2ChinaStr(start)).And("create_time__lte",
					helper.Milli2ChinaStr(end))
			}
		}
		cond = condition.TernaryOperator(params.Has("name"), cond.And("name__icontains", params.Get("name")), cond)
		cond = condition.TernaryOperator(params.Has("typeDictId"), cond.And("type_dict_id", params.Get("typeDictId")), cond)
		return cond
	}).All(&data) //追加排除status=-1的条件
	if err != nil {
		return nil, c.Pagination
	}
	return data, c.Pagination
}

// GetAllAirport 查询所有机场
func (c *AirportService) GetAllAirport() (list []*models.Airport, err error) {
	_, err = orm.NewOrm().QueryTable(new(models.Airport)).Filter("status__gte", schema.Enabled).All(&list)
	return
}

func (c *AirportService) GetSimpleAirportById(id int64) (*resp.SimpleAirport, error) {
	key := fmt.Sprintf(AirportCacheSimple, id)
	return global.GetCache[*resp.SimpleAirport](key, func() (*resp.SimpleAirport, error) {
		airport := models.Airport{}
		mAirport := new(models.Airport)
		err := orm.NewOrm().QueryTable(mAirport).Filter("id", id).One(&airport, mAirport.SimpleField()...)
		simpleAirPort := resp.SimpleAirport{}
		err = helper.CopyDeep(&simpleAirPort, airport)
		if err != nil {
			return nil, err
		}
		simpleAirPort.TypeName, _ = c.SysDictService.GetDictValueById(airport.TypeDictId)
		return &simpleAirPort, err
	})
}

// GetAirportCounts 查询所有省份机场数量
func (c *AirportService) GetAirportCounts() (list []*resp.ProvinceCount, err error) {
	qb, _ := orm.NewQueryBuilder("mysql")
	qb.Select("count(0) as count", "province", "province_code").From(
		"airport").Where("status>=?").GroupBy("province")
	_, err = orm.NewOrm().Raw(qb.String(), schema.Enabled).QueryRows(&list)
	return
}
